package io.vector.study.algorithm.permutation;

import com.alibaba.fastjson.JSON;

/**
 * Created by vector on 2017/3/6.
 */
public class Permutation {

    public <T extends Comparable<? super T>> void resolve(T[] array) {
        if (array == null || array.length == 0) {
            return ;
        }

        doResolve(array, 0, array.length - 1);
    }

    private <T extends Comparable<? super T>> void doResolve(T[] array, int start, int end) {

        if (start == end) {
            System.out.println(JSON.toJSONString(array));
            return ;
        }

        for (int index = start; index <= end; ++index) {
            swap(array, index, start);
            doResolve(array, start + 1, end);
            swap(array, index, start);
        }
    }

    private <T extends Comparable<? super T>> void swap(T[] array, int index1, int index2) {
        if (index1 == index2) {
            return ;
        }

        T temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    }

}
